import cv2, time
import numpy as np


def GetBackGround():
    cap = cv2.VideoCapture('sources/FixedPosVideo.avi')
    pBgModel = cv2.createBackgroundSubtractorMOG2()

    while (1):
        ret, frame = cap.read()
        fgmask = pBgModel.apply(frame)
        bgMask = pBgModel.getBackgroundImage()

        # fgmask = cv2.GaussianBlur(fgmask,(3,3),0)
        fgmask = cv2.medianBlur(fgmask, 3)
        ret1, fgmask = cv2.threshold(fgmask, 10, 255, cv2.THRESH_BINARY)

        image, contours, hierarchy = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        count = 0
        area_list = []
        for c in contours:
            area = cv2.contourArea(c)  # 区域面积
            if area < 200:
                continue
            count += 1

            a, b, w, h = cv2.boundingRect(c)  # 计算轮廓矩形（水平的）

            # 这次是真正的米所占像素数
            area = getArea(image, a, b, w, h)
            area_list.append((area, a, b, w, h))

            # 2.获取最小包围矩形
            # rect = cv2.minAreaRect(c)
            rect = np.array([[a,b],[a+w,b],[a+w,b+h],[a,b+h]])
            rect.reshape((4,2))
            # box = cv2.boxPoints(rect)
            box = np.int64(rect)
            print(type(box), box, box.shape)  # (4, 2)

            # 绘制最小包围矩形
            cv2.drawContours(frame, [box], 0, (0, 0, 255), 1)
            cv2.putText(frame, '%s:(%s,%s)' % (count, a, b), (a, b), cv2.FONT_HERSHEY_COMPLEX, 0.3, (0, 255, 0), 1)
            # print(count, a, b)
            # 绘制轮廓详细信息
            cv2.drawContours(frame, c, -1, (255, 255, 0), 1)  # c是描述这个轮廓的坐标数组，-1代表所有的轮廓都绘制

        cv2.imshow('origin', frame)  # 显示原始视频

        cv2.imshow('fgmask', fgmask)  # 显示提取出来的前景

        cv2.imshow('bgMask', bgMask)  # 显示提取出来的背景

        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break

    cap.release()
    cv2.destroyAllWindows()


def getArea(image, x, y, w, h):
    """
    获取图片的一个区域的图形 ,返回面积(像素值)
    image 是一个二值图，信息点是白色
    """
    zone = image[y:y + h, x:x + w]
    area = 0

    area = np.sum(zone == 255)  # 等价于后面的循环
    # for row in zone:
    #     for col in row:
    #         if col == 255:
    #             area += 1
    # print("area: ", area)
    return area


if __name__ == '__main__':
    GetBackGround()
